package edu.indiana.d2i.mapreduce;

import java.nio.ByteBuffer;

import org.apache.cassandra.dht.Token;
import org.apache.cassandra.utils.ByteBufferUtil;

@SuppressWarnings("rawtypes")
public class HectorColumnFamilyUtilies {
	@SuppressWarnings("unchecked")
	/* a method copied from org.apache.cassandra.dht.Range  */
	public static boolean withinRange(Token left, Token right, Token token) {
		if (compare(left,right) >= 0) {
			/*
			 * We are wrapping around, so the interval is (a,b] where a >= b,
			 * then we have 3 cases which hold for any given token k: (1) a < k
			 * -- return true (2) k <= b -- return true (3) b < k <= a -- return
			 * false
			 */
			if (token.compareTo(left) > 0)
				return true;
			else
				return right.compareTo(token) >= 0;
		} else {
			/*
			 * This is the range (a, b] where a < b.
			 */
			return (compare(token, left) > 0 && compare(right, token) >= 0);
		}
	}

	@SuppressWarnings("unchecked")
	private static int compare(Token left, Token right) {
		ByteBuffer l, r;

		if (left.token instanceof byte[]) {
			l = ByteBuffer.wrap((byte[]) left.token);
		} else if (left.token instanceof ByteBuffer) {
			l = (ByteBuffer) left.token;
		} else {
			// Handles other token types
			return left.compareTo(right);
		}

		if (right.token instanceof byte[]) {
			r = ByteBuffer.wrap((byte[]) right.token);
		} else {
			r = (ByteBuffer) right.token;
		}

		return ByteBufferUtil.compareUnsigned(l, r);
	}
}
